<template>
  <div class="list-page">
    <!-- <EmergencyVerticalTabNav /> -->
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="发生地点" prop="location">
                <el-input v-model="queryParams.location" placeholder="请输入发生地点" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="处置状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="处置状态" clearable>
                  <el-option :value="1" label="未启动" />
                  <el-option :value="2" label="进行中" />
                  <el-option :value="3" label="已控制" />
                  <el-option :value="4" label="已关闭" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="RefreshRight" @click="resetQuery">刷新</el-button>
              <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>

      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="happenTime" label="发生时间" width="180">
            <template #default="{ row }">
              {{ dayjs(row.happenTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="发生地点" min-width="120" />
          <el-table-column prop="description" label="事件描述" min-width="180" show-overflow-tooltip />
          <el-table-column prop="firstReportTime" label="首次报告时间" width="180">
            <template #default="{ row }">
              {{ dayjs(row.firstReportTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="处置状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 1 ? 'info' : row.status === 2 ? 'warning' : row.status === 3 ? 'success' : 'primary'"
                :class="['status-tag', `status-${row.status}`]">
                {{ row.status === 1 ? '未启动' : row.status === 2 ? '进行中' : row.status === 3 ? '已控制' : '已关闭' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button size="small" type="success" link @click="handleProcess(row)">
                处理
              </el-button>
              <el-button 
                v-if="row.status === 4"
                size="small" 
                type="warning" 
                link 
                @click="handleReset(row)"
              >
                重置
              </el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="60%"
        center
        destroy-on-close
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="发生时间" prop="happenTime">
            <el-date-picker v-model="form.happenTime" type="datetime" placeholder="选择发生时间"
              value-format="YYYY-MM-DD HH:mm:ss" :default-time="new Date(2000, 1, 1, 0, 0, 0)" class="w-full" />
          </el-form-item>
          <el-form-item label="发生地点" prop="location">
            <el-input v-model="form.location" placeholder="请输入发生地点" />
          </el-form-item>
          <el-form-item label="事件描述" prop="description">
            <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入事件描述" />
          </el-form-item>
          <el-form-item label="首次报告时间" prop="firstReportTime">
            <el-date-picker v-model="form.firstReportTime" type="datetime" placeholder="选择首次报告时间"
              value-format="YYYY-MM-DD HH:mm:ss" :default-time="new Date(2000, 1, 1, 0, 0, 0)" class="w-full" />
          </el-form-item>
          <el-form-item label="处置状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择处置状态" class="w-full">
              <el-option :value="1" label="未启动" />
              <el-option :value="2" label="进行中" />
              <el-option :value="3" label="已控制" />
              <el-option :value="4" label="已关闭" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 匹配弹窗 -->
      <el-dialog 
        title="预案匹配" 
        v-model="matchDialogVisible" 
        width="60%" 
        center
        destroy-on-close
        class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">预案匹配</span>
          </div>
        </template>
        <el-form ref="matchFormRef" :model="matchForm" :rules="matchRules" label-width="120px" class="dialog-form">
          <el-form-item label="预案类型" prop="planType">
            <el-radio-group v-model="matchForm.planType" @change="handlePlanTypeChange">
              <el-radio :label="1">总体预案</el-radio>
              <el-radio :label="2">专项预案</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择预案" prop="selectedPlan">
            <el-select v-model="matchForm.planId" placeholder="请选择预案" class="w-full" @change="handlePlanChange">
              <el-option v-for="plan in filteredPlanList" :key="plan.id" :label="plan.planName" :value="plan.id" />
            </el-select>
          </el-form-item>

          <!-- 预案详情展示区域 -->
          <template v-if="matchForm.selectedPlan">
            <el-form-item label="适用事件类型">
              <el-select v-model="matchForm.selectedPlan.eventCategory" disabled class="w-full">
                <el-option :value="1" label="自然灾害" />
                <el-option :value="2" label="事故灾难" />
                <el-option :value="3" label="公共卫生事件" />
                <el-option :value="4" label="社会安全事件" />
              </el-select>
            </el-form-item>
            <el-form-item label="适用事件等级">
              <el-select v-model="matchForm.selectedPlan.eventLevel" disabled class="w-full">
                <el-option :value="1" label="Ⅰ级" />
                <el-option :value="2" label="Ⅱ级" />
                <el-option :value="3" label="Ⅲ级" />
                <el-option :value="4" label="Ⅳ级" />
                <el-option :value="5" label="全部" />
              </el-select>
            </el-form-item>
            <el-form-item label="发布单位">
              <el-input v-model="matchForm.selectedPlan.publishUnit" disabled />
            </el-form-item>
            <el-form-item label="通知人员" prop="notifyPersonnel" required>
              <el-tree ref="deptTreeRef" :data="deptOptions" :props="{
                label: 'deptName',
                children: 'children'
              }" show-checkbox node-key="deptId" default-expand-all :render-content="renderContent" @check="handleCheck"
                @check-change="handleCheckChange" class="w-full" />
              <div v-if="deptOptions.length === 0" class="text-red-500 text-sm mt-1">
                暂无部门数据可选
              </div>
            </el-form-item>
          </template>
        </el-form>
        <!-- 添加通知表单到匹配弹窗中 -->
        <el-form v-if="matchForm.selectedPlan" ref="noticeFormRef" :model="noticeForm" :rules="noticeRules"
          label-width="100px" style="margin-top: 20px;">
          <el-form-item label="通知标题" prop="title">
            <el-input v-model="noticeForm.title" placeholder="请输入通知标题" />
          </el-form-item>
          <el-form-item label="通知内容" prop="content">
            <el-input v-model="noticeForm.content" type="textarea" :rows="8" placeholder="请输入通知内容" />
          </el-form-item>
          <el-form-item label="通知方式" prop="notifyMethod">
            <el-select v-model="noticeForm.notifyMethod" placeholder="请选择通知方式" style="width: 100%" multiple>
              <el-option v-for="dict in notifyMethodOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="事件级别" prop="warnLevel">
            <el-select v-model="noticeForm.warnLevel" placeholder="请选择事件级别" style="width: 100%">
              <el-option v-for="dict in warnLevelList" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="matchDialogVisible = false">取 消</el-button>
          <el-button type="success" @click="submitMatch">通 知</el-button>
        </template>
      </el-dialog>

      <!-- 记录弹窗 -->
      <el-dialog 
        title="处置记录" 
        v-model="recordDialogVisible" 
        width="50%" 
        center
        destroy-on-close
        class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">处置记录</span>
          </div>
        </template>
        <el-form ref="recordFormRef" :model="recordForm" label-width="120px" class="dialog-form">
          <el-form-item label="处置时间" prop="handleTime">
            <el-date-picker v-model="recordForm.handleTime" type="datetime" placeholder="选择处置时间" class="w-full" />
          </el-form-item>
          <el-form-item label="处置人员" prop="handler">
            <el-input v-model="recordForm.handler" placeholder="请输入处置人员" />
          </el-form-item>
          <el-form-item label="处置措施" prop="measures">
            <el-input type="textarea" v-model="recordForm.measures" :rows="3" placeholder="请输入处置措施" />
          </el-form-item>
          <el-form-item label="处置结果" prop="result">
            <el-input type="textarea" v-model="recordForm.result" :rows="3" placeholder="请输入处置结果" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="recordDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRecord">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 总结弹窗 -->
      <el-dialog 
        title="事件总结" 
        v-model="summaryDialogVisible" 
        width="60%" 
        center
        destroy-on-close
        class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">事件总结</span>
          </div>
        </template>
        <el-form ref="summaryFormRef" :model="summaryForm" label-width="120px" class="dialog-form">
          <el-form-item label="工作类型" prop="workType">
            <el-select v-model="summaryForm.workType" disabled class="w-full">
              <el-option value="应急处置" label="应急处置" />
            </el-select>
          </el-form-item>
          <el-form-item label="总结时间" prop="summaryTime">
            <el-date-picker v-model="summaryForm.summaryTime" type="datetime" placeholder="选择总结时间"
              value-format="YYYY-MM-DD HH:mm:ss" class="w-full" />
          </el-form-item>
          <el-form-item label="负责人" prop="responsible">
            <el-input v-model="summaryForm.responsible" placeholder="请输入负责人姓名" />
          </el-form-item>
          <el-form-item label="工作内容" prop="workContent">
            <el-input type="textarea" v-model="summaryForm.workContent" :rows="3" placeholder="请详细描述工作内容" />
          </el-form-item>
          <el-form-item label="主要成果" prop="mainAchievements">
            <el-input type="textarea" v-model="summaryForm.mainAchievements" :rows="3" placeholder="请描述工作取得的主要成果" />
          </el-form-item>
          <el-form-item label="存在问题" prop="existingProblems">
            <el-input type="textarea" v-model="summaryForm.existingProblems" :rows="3" placeholder="请描述工作中存在的问题" />
          </el-form-item>
          <el-form-item label="改进建议" prop="improvements">
            <el-input type="textarea" v-model="summaryForm.improvements" :rows="3" placeholder="请提出改进建议" />
          </el-form-item>
          <el-form-item label="相关附件">
            <el-upload class="upload-demo" action="/api/common/upload" multiple>
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传Word、Excel、PDF等文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="summaryForm.remarks" :rows="2" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="summaryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSummary">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 评估弹窗 -->
      <el-dialog 
        title="事件评估" 
        v-model="evaluateDialogVisible" 
        width="50%" 
        center
        destroy-on-close
        class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">事件评估</span>
          </div>
        </template>
        <el-form ref="evaluateFormRef" :model="evaluateForm" label-width="120px" class="dialog-form">
          <el-form-item label="响应及时性" prop="responseTimeliness">
            <el-rate v-model="evaluateForm.responseTimeliness" :texts="['极差', '较差', '一般', '良好', '优秀']" show-text />
          </el-form-item>
          <el-form-item label="处置有效性" prop="handleEffectiveness">
            <el-rate v-model="evaluateForm.handleEffectiveness" :texts="['极差', '较差', '一般', '良好', '优秀']" show-text />
          </el-form-item>
          <el-form-item label="资源利用率" prop="resourceUtilization">
            <el-rate v-model="evaluateForm.resourceUtilization" :texts="['极差', '较差', '一般', '良好', '优秀']" show-text />
          </el-form-item>
          <el-form-item label="评估意见" prop="opinion">
            <el-input type="textarea" v-model="evaluateForm.opinion" :rows="3" placeholder="请输入评估意见" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="evaluateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEvaluate">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 重置处理对话框 -->
      <el-dialog
        v-model="resetProcessDialog"
        title="重置处理状态"
        width="30%"
        center
        destroy-on-close
        class="custom-dialog"
        append-to-body
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">重置处理状态</span>
          </div>
        </template>
        <div class="reset-dialog-content">
          <el-alert
            title="该事件的流程状态已完成，但事件状态未结束"
            type="warning"
            :closable="false"
            show-icon
            style="margin-bottom: 20px;"
          />
          <p>事件ID: {{ eventData.eventId }}</p>
          <p>事件描述: {{ eventData.description }}</p>
          <p>当前流程状态: 已完成 ({{ eventData.flowStatus }})</p>
          <p>当前事件状态: {{ getStatusName(eventData.status) }} ({{ eventData.status }})</p>
          <p>是否要重置处理流程状态？重置后，您可以继续完成事件处理。</p>
        </div>
        <template #footer>
          <el-button @click="resetProcessDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmResetProcess">确认重置</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick, getCurrentInstance, watch, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getEmergencyEventList,
  getEmergencyEventById,
  addEmergencyEvent,
  updateEmergencyEvent,
  deleteEmergencyEvent
} from "@/api/bridge/command/event";
import { getEmergencyPlanList, getEmergencyPlanById } from "@/api/bridge/command/emergency";
import { getPlanNoticeRecord } from "@/api/bridge/command/dept";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { Plus, Document, RefreshRight, Search } from '@element-plus/icons-vue';
import { listDept } from "@/api/system/dept";
import { getUserInfoList } from "@/api/bridge/user/user";
import { listData } from "@/api/system/dict/data";
import type { DictDataQuery } from "@/api/system/dict/data/types";
import useUserStore from "@/store/modules/user";
import { addNotice, publishNotice } from "@/api/bridge/command/notice";
import EmergencyVerticalTabNav from "./components/EmergencyVerticalTabNav.vue";

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const queryFormRef = ref();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  happenTime: null,
  location: null,
  status: null
});

// 搜索操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.happenTime = null;
  queryParams.location = null;
  queryParams.status = null;
  handleQuery();
};

// 路由
const router = useRouter();

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  happenTime: "",
  location: "",
  description: "",
  firstReportTime: "",
  status: 1
});

// 表单校验规则
const rules = {
  happenTime: [{ required: true, message: "请选择发生时间", trigger: "change" }],
  location: [{ required: true, message: "请输入发生地点", trigger: "blur" }],
  description: [{ required: true, message: "请输入事件描述", trigger: "blur" }],
  firstReportTime: [{ required: true, message: "请选择首次报告时间", trigger: "change" }],
  status: [{ required: true, message: "请选择处置状态", trigger: "change" }]
};

// 匹配弹窗相关
const matchDialogVisible = ref(false);
const matchFormRef = ref();
const matchForm = ref({
  planType: 1,
  planId: null,
  selectedPlan: null,
  notifyPersonnel: []
});

const emergencyPlanList = ref([]);
const deptOptions = ref([]);
const deptTreeRef = ref();

// 记录弹窗相关
const recordDialogVisible = ref(false);
const recordFormRef = ref();
const recordForm = ref({
  handleTime: '',
  handler: '',
  measures: '',
  result: ''
});

// 总结弹窗相关
const summaryDialogVisible = ref(false);
const summaryFormRef = ref();
const summaryForm = ref({
  workType: "应急处置",
  summaryTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  responsible: "",
  workContent: "",
  mainAchievements: "",
  existingProblems: "",
  improvements: "",
  status: 1,
  attachments: [],
  remarks: ""
});

// 评估弹窗相关
const evaluateDialogVisible = ref(false);
const evaluateFormRef = ref();
const evaluateForm = ref({
  responseTimeliness: 3,
  handleEffectiveness: 3,
  resourceUtilization: 3,
  opinion: ''
});

// 添加通知相关的响应式数据
const noticeFormRef = ref();
const noticeForm = ref({
  title: '应急事件通知',
  content: '',
  warnType: "6",
  status: 1,
  notifyMethod: [],
  sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  userId: useUserStore().userId,
  eventId: '',
  warnLevel: ''
});

// 添加通知表单验证规则
const noticeRules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  notifyMethod: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  warnLevel: [{ required: true, message: '请选择事件级别', trigger: 'change' }]
};

// 添加通知方式选项
const notifyMethodOptions = ref<any[]>([]);

// 获取通知方式字典
const getNotifyMethodDict = async () => {
  const queryParams: DictDataQuery = {
    dictType: "notification_method",
    pageNum: 1,
    pageSize: 100,
    dictName: "",
    dictLabel: ""
  };
  const res = await listData(queryParams);
  notifyMethodOptions.value = res.rows;
};

// 格式化通知内容
const formatNoticeContent = (selectedPlan: any) => {
  if (!selectedPlan) return '';
  
  const content = [
    `预案类型：${selectedPlan.planType === 1 ? '总体预案' : '专项预案'}`,
    `预案名称：${selectedPlan.planName}`,
    `适用事件类型：${selectedPlan.eventCategory}`,
    `适用事件等级：${selectedPlan.eventLevel}`,
    `发布单位：${selectedPlan.publishUnit}`,
  ].join("\n");
  return content;
};

// 获取部门树状数据
const getDeptTreeData = async () => {
  try {
    // 获取所有部门数据
    const deptRes = await listDept({
      pageNum: 1,
      pageSize: 10000
    });

    // 获取所有用户数据
    const userRes = await getUserInfoList({
      pageNum: 1,
      pageSize: 10000
    });

    if (deptRes.code === 200 && deptRes.data && deptRes.data.length > 0) {
      // 构建用户映射表，按部门ID分组
      const userMap = {};
      if (userRes.code === 200 && userRes.rows) {
        userRes.rows.forEach(user => {
          const deptId = String(user.deptId);
          if (!userMap[deptId]) {
            userMap[deptId] = [];
          }
          userMap[deptId].push({
            userId: user.userId,
            userName: user.userName,
            nickName: user.nickName,
            deptId: deptId,
            deptName: user.deptName
          });
        });
      }

      // 构建树形结构
      const buildDeptTree = (data) => {
        const normalize = data.map(item => ({
          ...item,
          deptId: String(item.deptId),
          parentId: String(item.parentId),
          users: userMap[String(item.deptId)] || []
        }));

        const map = {};
        normalize.forEach(item => {
          map[item.deptId] = { ...item, children: [] };
        });

        const tree = [];
        normalize.forEach(item => {
          const parentId = item.parentId;
          const id = item.deptId;

          if (map[parentId]) {
            map[parentId].children.push(map[id]);
          } else {
            if (parentId === '0') {
              tree.push(map[id]);
            }
          }
        });

        return tree;
      };

      const treeData = buildDeptTree(deptRes.data);
      if (treeData.length === 0 && deptRes.data.length > 0) {
        const { proxy } = getCurrentInstance();
        if (proxy?.handleTree) {
          deptOptions.value = proxy.handleTree(deptRes.data, 'deptId', 'parentId');
        } else {
          deptOptions.value = deptRes.data.map(item => ({
            ...item,
            deptId: String(item.deptId),
            label: item.deptName,
            value: String(item.deptId),
            children: [],
            users: userMap[String(item.deptId)] || []
          }));
        }
      } else {
        deptOptions.value = treeData;
      }
    } else {
      deptOptions.value = [];
    }
  } catch (error) {
    console.error("获取部门数据失败:", error);
    deptOptions.value = [];
  }
};

// 自定义节点渲染
const renderContent = (h, { node, data }) => {
  return h('div', { class: 'custom-tree-node' }, [
    h('span', { class: 'node-label' }, [
      h('span', null, node.label),
      h('span', { class: 'user-count' }, ` (${data.users?.length || 0}人)`)
    ]),
    h('div', { class: 'user-list' },
      data.users?.map(user =>
        h('div', {
          class: 'user-item',
          key: user.userId,
          onClick: (e) => {
            e.stopPropagation();
            handleUserSelect(user, node);
          }
        }, [
          h('el-checkbox', {
            modelValue: isUserSelected(user),
            'onUpdate:modelValue': (val) => handleUserCheck(user, val),
            onClick: (e) => e.stopPropagation()
          }, user.nickName || user.userName)
        ])
      )
    )
  ]);
};

// 处理部门选择
const handleCheck = (data, { checkedKeys, checkedNodes, halfCheckedKeys, halfCheckedNodes }) => {
  updateSelectedUsers();
};

// 处理部门选择状态变化
const handleCheckChange = (data, checked, indeterminate) => {
  updateParentNodeStatus(data);
};

// 处理用户选择
const handleUserSelect = (user, node) => {
  event.stopPropagation();
};

// 处理用户复选框变化
const handleUserCheck = (user, checked) => {
  const userKey = `${user.deptId}-${user.userId}`;
  if (checked) {
    if (!matchForm.value.notifyPersonnel.includes(userKey)) {
      matchForm.value.notifyPersonnel.push(userKey);
    }
  } else {
    matchForm.value.notifyPersonnel = matchForm.value.notifyPersonnel.filter(key => key !== userKey);
  }

  updateDeptNodeStatus(user.deptId);
};

// 检查用户是否被选中
const isUserSelected = (user) => {
  const userKey = `${user.deptId}-${user.userId}`;
  return matchForm.value.notifyPersonnel.includes(userKey);
};

// 更新选中的用户列表
const updateSelectedUsers = () => {
  const tree = deptTreeRef.value;
  if (!tree) return;

  const checkedNodes = tree.getCheckedNodes();
  const halfCheckedNodes = tree.getHalfCheckedNodes();

  const selectedUsers = [];

  checkedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (!selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });

  halfCheckedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (isUserSelected(user) && !selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });

  matchForm.value.notifyPersonnel = selectedUsers;
};

// 根据部门ID和用户ID查找用户信息
const findUserInfo = (deptId, userId) => {
  const findInDept = (depts) => {
    for (const dept of depts) {
      if (String(dept.deptId) === String(deptId)) {
        const user = dept.users?.find(u => String(u.userId) === String(userId));
        if (user) return user;
      }
      if (dept.children) {
        const found = findInDept(dept.children);
        if (found) return found;
      }
    }
    return null;
  };

  return findInDept(deptOptions.value);
};

// 更新部门节点的选中状态
const updateDeptNodeStatus = (deptId) => {
  const tree = deptTreeRef.value;
  if (!tree) return;

  const node = tree.getNode(deptId);
  if (!node) return;

  const selectedUsers = matchForm.value.notifyPersonnel.filter(key =>
    key.includes('-') && key.startsWith(`${deptId}-`)
  );

  const allUsers = node.data.users || [];

  if (selectedUsers.length === allUsers.length && allUsers.length > 0) {
    node.checked = true;
    node.indeterminate = false;
  } else if (selectedUsers.length > 0) {
    node.checked = false;
    node.indeterminate = true;
  } else {
    node.checked = false;
    node.indeterminate = false;
  }

  // 更新父节点状态
  if (node.parent && node.parent.key !== 0) {
    updateParentNodeStatus(node.data);
  }
};

// 更新父节点状态
const updateParentNodeStatus = (data) => {
  const tree = deptTreeRef.value;
  if (!tree) return;

  const node = tree.getNode(data.deptId);
  if (!node || !node.parent || node.parent.key === 0) return;

  const parentNode = node.parent;
  const siblings = parentNode.childNodes;

  const allChecked = siblings.every(sibling => sibling.checked);
  const someChecked = siblings.some(sibling => sibling.checked || sibling.indeterminate);

  parentNode.checked = allChecked;
  parentNode.indeterminate = !allChecked && someChecked;

  if (parentNode.parent && parentNode.parent.key !== 0) {
    updateParentNodeStatus(parentNode.data);
  }
};

// 添加全局样式，确保与emergency-response组件一致
const treeStyle = document.createElement('style');
treeStyle.textContent = `
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-count {
  color: #909399;
  font-size: 12px;
}

.user-list {
  margin-left: 24px;
  padding: 4px 0;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 2px 0;
  cursor: pointer;
}

.user-item:hover {
  background-color: var(--el-fill-color-light);
}
`;
document.head.appendChild(treeStyle);

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    const res = await getEmergencyEventList(params);
    if (res.code === 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增应急事件";
  form.value = {
    id: "",
    happenTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    location: "",
    description: "",
    firstReportTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    status: 1
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    const res = await getEmergencyEventById(row.id);
    if (res.code === 200) {
      form.value = {
        ...res.data,
        happenTime: res.data.happenTime ? dayjs(res.data.happenTime).format('YYYY-MM-DD HH:mm:ss') : '',
        firstReportTime: res.data.firstReportTime ? dayjs(res.data.firstReportTime).format('YYYY-MM-DD HH:mm:ss') : ''
      };
      dialogTitle.value = "编辑应急事件";
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该应急事件吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const res = await deleteEmergencyEvent(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form.value };

        if (form.value.id) {
          const res = await updateEmergencyEvent(submitData);
          if (res.code === 200) {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "修改失败");
          }
        } else {
          const res = await addEmergencyEvent(submitData);
          if (res.code === 200) {
            ElMessage.success("新增成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "新增失败");
          }
        }
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

// 获取预案通知记录
const getPlanNoticeRecords = async (planId) => {
  try {
    const res = await getPlanNoticeRecord({ planId });
    if (res.code === 200 && res.rows) {
      // 将通知记录转换为前端需要的格式
      const selectedPersonnel = res.rows.map(record => {
        if (record.personnelId) {
          // 如果有用户ID，使用 deptId-userId 格式
          return `${record.departmentId}-${record.personnelId}`;
        } else {
          // 如果只有部门ID，只返回部门ID
          return String(record.departmentId);
        }
      }).filter(Boolean);

      // 更新表单中的选中人员
      matchForm.value.notifyPersonnel = selectedPersonnel;

      // 在树形控件中设置选中状态
      nextTick(async () => {
        if (deptTreeRef.value) {
          // 先重置所有选中状态
          deptTreeRef.value.setCheckedKeys([]);

          // 处理部门的选中状态
          const deptIds = new Set(res.rows
            .map(record => String(record.departmentId))
            .filter(Boolean));

          // 设置部门的选中状态
          deptIds.forEach(deptId => {
            const node = deptTreeRef.value.getNode(deptId);
            if (node) {
              deptTreeRef.value.setChecked(node.key, true, false);
            }
          });

          // 处理用户的选中状态
          selectedPersonnel.forEach(key => {
            if (key.includes('-')) {
              const [deptId] = key.split('-');
              updateDeptNodeStatus(deptId);
            }
          });
        }
      });
    } else {
      matchForm.value.notifyPersonnel = [];
    }
  } catch (error) {
    console.error("获取预案通知记录失败:", error);
    matchForm.value.notifyPersonnel = [];
  }
};

// 处理匹配
const handleMatch = async (row) => {
  // 保存当前行的id到form中，以便在提交时使用
  form.value.id = row.id;
  
  matchForm.value = {
    planType: 1,
    planId: null,
    selectedPlan: null,
    notifyPersonnel: []
  };
  await getDeptTreeData();
  await loadEmergencyPlanList();
  matchDialogVisible.value = true;
};

// 处理记录
const handleRecord = (row) => {
  router.push(`/monitor/event/event-record?eventId=${row.id}`);
};

// 跳转到事件处置记录页面
const goToEventRecord = () => {
  router.push('/coordination-command/event-record');
};

// 处理评估
const handleEvaluate = (row) => {
  evaluateForm.value = {
    responseTimeliness: 3,
    handleEffectiveness: 3,
    resourceUtilization: 3,
    opinion: ''
  };
  evaluateDialogVisible.value = true;
};

// 提交匹配
const submitMatch = async () => {
  try {
    if (!matchFormRef.value) return;
    
    // 验证表单
    await matchFormRef.value.validate();
    
    if (!matchForm.value.planId || !matchForm.value.selectedPlan) {
      ElMessage.warning('请先选择一个预案');
      return;
    }

    // 验证通知表单
    await noticeFormRef.value.validate();

    // 获取所有选中的部门节点
    const checkedDeptNodes = deptTreeRef.value ? deptTreeRef.value.getCheckedNodes() : [];
    const halfCheckedDeptNodes = deptTreeRef.value ? deptTreeRef.value.getHalfCheckedNodes() : [];
    const allCheckedDepts = [...checkedDeptNodes, ...halfCheckedDeptNodes];

    // 创建部门ID映射，方便查找
    const deptMap = {};
    const collectDepts = (nodes) => {
      nodes.forEach(node => {
        deptMap[node.deptId] = node;
        if (node.children && node.children.length > 0) {
          collectDepts(node.children);
        }
      });
    };
    collectDepts(deptOptions.value);

    // 构建通知记录数据
    const notifyList = [];

    // 首先处理用户选择(带有 deptId-userId 格式的记录)
    matchForm.value.notifyPersonnel.forEach(userKey => {
      if (userKey.includes('-')) {
        const [deptId, userId] = userKey.split('-');
        // 从部门树中查找用户信息
        const userInfo = findUserInfo(deptId, userId);
        if (userInfo) {
          notifyList.push({
            departmentId: deptId,
            departmentName: userInfo.deptName,
            personnelId: userId,
            personnelName: userInfo.nickName || userInfo.userName
          });
        }
      }
    });

    // 然后处理部门选择(所有选中的部门，不带用户ID)
    allCheckedDepts.forEach(dept => {
      const deptId = String(dept.deptId);
      // 检查该部门是否已经有用户级别的记录
      const hasDeptUserRecord = notifyList.some(record =>
        String(record.departmentId) === deptId && record.personnelId
      );

      // 如果没有用户级别的记录，则添加部门级别的记录
      if (!hasDeptUserRecord) {
        notifyList.push({
          departmentId: deptId,
          departmentName: dept.deptName,
          personnelId: null,  // 无用户ID
          personnelName: null  // 无用户名
        });
      }
    });

    if (notifyList.length === 0) {
      ElMessage.warning('请选择至少一个通知对象');
      return;
    }

    // 准备通知数据
    const noticeData = {
      ...noticeForm.value,
      notifyMethod: Array.isArray(noticeForm.value.notifyMethod) 
        ? noticeForm.value.notifyMethod.join(',') 
        : noticeForm.value.notifyMethod,
      eventId: form.value.id,
      warnLevel: noticeForm.value.warnLevel
    };

    // 发送通知
    const res = await addNotice(noticeData);
    if (res.code === 200) {
      await publishNotice(res.data);
      ElMessage.success('通知已发送');
      matchDialogVisible.value = false;
    }
  } catch (error) {
    console.error('发送通知失败:', error);
    ElMessage.error('发送通知失败');
  }
};

// 提交记录
const submitRecord = () => {
  ElMessage.success('记录成功');
  recordDialogVisible.value = false;
};

// 提交总结
const submitSummary = () => {
  ElMessage.success('总结成功');
  summaryDialogVisible.value = false;
};

// 提交评估
const submitEvaluate = () => {
  ElMessage.success('评估成功');
  evaluateDialogVisible.value = false;
};

// 计算筛选后的预案列表
const filteredPlanList = computed(() => {
  return emergencyPlanList.value.filter(plan => plan.planType === matchForm.value.planType);
});

// 获取应急预案列表方法
const loadEmergencyPlanList = async () => {
  try {
    const res = await getEmergencyPlanList({
      pageNum: 1,
      pageSize: 1000000
    });
    if (res.code === 200) {
      emergencyPlanList.value = res.rows;
    }
  } catch (error) {
    console.error("获取应急预案列表失败:", error);
  }
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取状态名称
const getStatusName = (status) => {
  if (status === 1) return '未启动';
  if (status === 2) return '进行中';
  if (status === 3) return '已控制';
  if (status === 4) return '已关闭';
  return '未知状态';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    1: 'info',     // 未启动 - 灰色
    2: 'warning',  // 进行中 - 黄色
    3: 'success',  // 已控制 - 绿色
    4: 'primary'   // 已关闭 - 蓝色
  };
  return statusMap[status] || '';
};

// 处理预案变化
const handlePlanChange = async (planId) => {
  try {
    if (!planId) {
      matchForm.value.selectedPlan = null;
      matchForm.value.notifyPersonnel = [];
      noticeForm.value.content = '';
      return;
    }

    // 先从当前列表中查找预案
    const plan = emergencyPlanList.value.find(p => p.id === planId);
    if (plan) {
      matchForm.value.selectedPlan = { ...plan };
      noticeForm.value.content = formatNoticeContent(plan);
      // 设置当前事件ID
      noticeForm.value.eventId = form.value.id;
    } else {
      // 如果在列表中找不到，则通过API获取
      const res = await getEmergencyPlanById(planId);
      if (res.code === 200) {
        matchForm.value.selectedPlan = res.data;
        noticeForm.value.content = formatNoticeContent(res.data);
        // 设置当前事件ID
        noticeForm.value.eventId = form.value.id;
      } else {
        ElMessage.error("获取预案详情失败");
        return;
      }
    }

    // 获取通知记录
    await getPlanNoticeRecords(planId);
  } catch (error) {
    console.error("处理预案变化失败:", error);
    ElMessage.error("获取预案详情失败");
  }
};

// 处理预案类型变化
const handlePlanTypeChange = () => {
  // 重置表单
  matchForm.value = {
    planType: matchForm.value.planType,
    planId: null,
    selectedPlan: null,
    notifyPersonnel: []
  };
  noticeForm.value = {
    title: '应急事件通知',
    content: '',
    warnType: "6",
    status: 1,
    notifyMethod: [],
    sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    userId: useUserStore().userId,
    eventId: form.value.id, // 保持eventId不变
    warnLevel: ''
  };
};

// 在 script setup 部分添加以下代码
// const queryParams = ref({
//   dictType: "",
//   pageNum: 1,
//   pageSize: 100,
//   dictName: "",
//   dictLabel: ""
// });

const warnLevelList = ref<Array<{
  dictValue: string;
  dictLabel: string;
}>>([]);

// 添加获取预警级别字典的方法
const getWarnLevelDict = async () => {
  queryParams.value.dictType = "warn_level";
  const res = await listData(queryParams.value);
  if (res.code === 200) {
    warnLevelList.value = res.rows;
  }
};

// 添加 matchForm 的验证规则
const matchRules = {
  planType: [{ required: true, message: '请选择预案类型', trigger: 'change' }],
  planId: [{ required: true, message: '请选择预案', trigger: 'change' }],
  notifyPersonnel: [{ required: true, message: '请至少选择一个通知对象', trigger: 'change' }]
};

// 处理按钮点击事件
const handleProcess = (row) => {
  // 如果状态为已关闭，直接跳转
  if (row.status === 4) {
    router.push({
      path: '/monitor/flowLog',
      query: { eventId: row.id }
    });
    return;
  }

  // 如果flowStatus为7但status不为4，提示重置处理
  if (row.flowStatus === 7 && row.status !== 4) {
    ElMessageBox.confirm(
      `该事件已经完成全部流程但尚未关闭。是否重置为上一步(应急总结阶段)以便继续处理？`,
      '提示',
      {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        // 将flowStatus设置为6（应急总结阶段）
        const updateData = {
          ...row,
          flowStatus: 6
        };
        const res = await updateEmergencyEvent(updateData);
        if (res.code === 200) {
          ElMessage.success('已重置处理状态');
          router.push({
            path: '/monitor/flowLog',
            query: { eventId: row.id }
          });
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('重置事件状态失败:', error);
        ElMessage.error('操作失败');
      }
    }).catch(() => {
      // 用户取消操作
    });
    return;
  }

  ElMessageBox.confirm(
    `是否开始进行"${row.description}"事件的流程处理？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 只有当flowStatus为空或为0时才设置为1，否则保留原值
      const updateData = {
        ...row,
        flowStatus: (!row.flowStatus || row.flowStatus === 0) ? 1 : row.flowStatus
      };
      const res = await updateEmergencyEvent(updateData);
      if (res.code === 200) {
        ElMessage.success('已开始处理事件');
        router.push({
          path: '/monitor/flowLog',
          query: { eventId: row.id }
        });
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('处理事件失败:', error);
      ElMessage.error('操作失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 重置处理对话框
const resetProcessDialog = ref(false);

// 确认重置处理
const confirmResetProcess = async () => {
  try {
    const params = {
      id: eventData.value.id,
      flowStatus: 6 // 重置为待完成状态
    };
    const res = await updateEmergencyEvent(params);
    if (res.code === 200) {
      ElMessage.success('处理状态已重置');
      resetProcessDialog.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || '重置失败');
    }
  } catch (error) {
    console.error('重置处理状态失败:', error);
    ElMessage.error('操作失败');
  }
};

// 处理行点击事件
const handleRowClick = (row) => {
  // 保存点击行数据到eventData
  eventData.value = row;
  
  // 检查流程状态与事件状态
  if (row.flowStatus === 7 && row.status !== 4) {
    // 显示重置对话框
    resetProcessDialog.value = true;
  } else {
    // 正常打开详情抽屉
    drawer.value = true;
  }
};

// 添加重置处理方法
const handleReset = (row) => {
  ElMessageBox.confirm(
    '确定要重置该事件的处理状态吗？重置后事件将回到处理中状态。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const updateData = {
        ...row,
        status: 2, // 设置为进行中状态
        flowStatus: 6 // 设置为应急总结阶段
      };
      const res = await updateEmergencyEvent(updateData);
      if (res.code === 200) {
        ElMessage.success('事件状态已重置');
        getList(); // 刷新列表
        router.push({
          path: '/monitor/flowLog',
          query: { eventId: row.id }
        });
      } else {
        ElMessage.error(res.msg || '重置失败');
      }
    } catch (error) {
      console.error('重置事件状态失败:', error);
      ElMessage.error('操作失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

onMounted(() => {
  getList();
  getNotifyMethodDict();
  getWarnLevelDict();
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: $bg-color-overlay;
  padding: 16px;
  border-radius: $border-radius;
}

.search-input {
  width: 300px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

.reset-dialog-content {
  padding: 16px;
  line-height: 1.6;

  p {
    margin-bottom: 8px;
  }
}

/* 状态标签特殊样式 */
.status-tag {
  font-weight: bold;
  
  &.status-1 {
    background: var(--el-color-info-light-8) !important;
    color: var(--el-color-info-dark-2) !important;
    border-color: var(--el-color-info) !important;
  }
  
  &.status-2 {
    background: var(--el-color-warning-light-8) !important;
    color: var(--el-color-warning-dark-2) !important;
    border-color: var(--el-color-warning) !important;
  }
  
  &.status-3 {
    background: var(--el-color-success-light-8) !important;
    color: var(--el-color-success-dark-2) !important; 
    border-color: var(--el-color-success) !important;
  }
  
  &.status-4 {
    background: var(--el-color-primary-light-8) !important;
    color: var(--el-color-primary-dark-2) !important;
    border-color: var(--el-color-primary) !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.w-full {
  width: 100%;
}
</style>